﻿using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using PoemGame.Domain.GameAggregate;

namespace PoemGame.Repository.EF
{
    /// <summary>
    /// 游戏存储库， 需要与Unit of Work一起工作
    /// 需要调用工作单元的SaveChanges进行实际保存
    /// </summary>
    public class GameRepositoryUoW:IGameRepository
    {
        private readonly PoemGameDbContext dbContext;
        public GameRepositoryUoW(PoemGameDbContext dbContext)
        {
            this.dbContext = dbContext;
        }
        /// <summary>
        /// 根据Id获取游戏
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Game?> GetAsync(Guid id)
        {
            return await dbContext.Games.FindAsync(id);
        }
        /// <summary>
        /// 添加游戏，如果Id为空则自动产生
        /// </summary>
        /// <param name="game"></param>
        /// <returns></returns>
        public async Task<Guid> AddAsync(Game game)
        {
            await dbContext.Games.AddAsync(game);
            return game.Id;
        }
        /// <summary>
        /// 更新游戏，只产生跟踪对象，不对数据库进行操作
        /// </summary>
        /// <param name="game"></param>
        /// <returns></returns>
        public async Task UpdateAsync(Game game)
        {
              dbContext.Update(game);
        }
        /// <summary>
        /// 移除游戏，只是移除跟踪对象，不对数据库操作
        /// </summary>
        /// <param name="game"></param>
        /// <returns></returns>
        public async Task RemoveAsync(Game game)
        {
            dbContext.Remove(game);
        }
        /// <summary>
        /// 获取所有游戏
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<Game>> GetAllAsync()
        {
            return await dbContext.Games.ToListAsync(); ;
        }
        /// <summary>
        /// 根据条件获取游戏
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public async Task<IEnumerable<Game>> GetByConditionAsync(Expression<Func<Game, bool>> predicate)
        {
            return await dbContext.Games.Where(predicate).ToListAsync();
        }
    }
}